<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\FetchContractDocumentJob;
use App\Models\ContractSignHistory;
use App\Models\Task;
use App\Models\TaskApplication;
use App\Models\Freelancer;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class ContractSignCallbackController extends Controller
{
    public function notify(Request $request)
    {
        $payload = $request->all();
        Log::info('[ContractSign][Callback] 收到通知', $payload);

        $data = $payload['data'] ?? null;
        if (is_string($data)) {
            $decoded = json_decode($data, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $data = $decoded;
            }
        }

        if (! is_array($data)) {
            Log::warning('[ContractSign][Callback] data 解析失败');
            return response()->json([
                'success' => false,
                'msg' => '处理失败',
            ]);
        }

        $applyNo = $data['applyNo'] ?? null;
        $signStatus = (int) ($data['signStatus'] ?? 0);

        if (! $applyNo) {
            Log::warning('[ContractSign][Callback] 缺少 applyNo');
            return response()->json([
                'success' => false,
                'msg' => '处理失败',
            ]);
        }

        $history = ContractSignHistory::where('apply_no', $applyNo)->first();
        if (! $history) {
            Log::warning('[ContractSign][Callback] 未找到历史记录', ['applyNo' => $applyNo]);
            return response()->json([
                'success' => false,
                'msg' => '处理失败',
            ]);
        }

        if ($signStatus === 3) {
            $status = 'approved';
        } elseif ($signStatus === 2) {
            $status = 'rejected';
        } else {
            $status = 'pending';
        }

        $history->status = $status;

        $application = null;
        if ($signStatus === 3) {
            $application = $this->createApprovedApplication($history);
            if ($application) {
                $history->application_id = $application->id;
            }
        }

        $history->save();

        if ($signStatus === 3) {
            FetchContractDocumentJob::dispatch($history->apply_no);
        }

        return response()->json([
            'success' => true,
            'msg' => '处理成功',
        ]);
    }

    protected function createApprovedApplication(ContractSignHistory $history): ?TaskApplication
    {
        $freelancer = Freelancer::find($history->freelancer_id);
        $task = Task::with('tenant')->find($history->task_id);

        if (! $freelancer || ! $task) {
            Log::warning('[ContractSign][Callback] 无法创建报名记录，缺少任务或自由职业者', [
                'history' => $history->toArray(),
            ]);
            return null;
        }

        $existing = TaskApplication::where('task_id', $task->id)
            ->where('freelancer_id', (string)$freelancer->id)
            ->latest('id')
            ->first();
        Log::info('[ContractSign][Callback]', ['existing' => $existing->id ?? null]);
        if ($existing && $existing->status === 'approved') {
            return $existing;
        }

        $now = Carbon::now();

        $application = TaskApplication::create([
            'task_id' => $task->id,
            'freelancer_id' => $freelancer->id,
            'tenant_id' => $task->tenant_id,
            'name' => $freelancer->real_name ?? $freelancer->name,
            'phone' => $freelancer->phone,
            'email' => $freelancer->email ?? '',
            'id_card' => $freelancer->id_card ?? '',
            'experience' => '',
            'status' => 'approved',
            'applied_at' => $now,
            'processed_at' => $now,
            'reviewed_at' => $now,
            'source' => 'contract-sign',
            'application_note' => '合同签署成功自动入职',
            'review_note' => '合同签署成功',
        ]);

        return $application;
    }
}
